import { View, Text, TextInput, TouchableOpacity, FlatList, StyleSheet } from 'react-native'
import { useContext, useState } from 'react'
import TodoItem from './TodoItem';
import { MyColors } from '../styles/MyColors';
import { ThemeContext } from '../context/ThemeContext';

interface Todo {
    id: string;          // 待办项的唯一标识符
    title: string;       // 待办项的标题
    isCompleted: boolean; // 是否完成
}

export default function TodoList() {
    const theme = useContext(ThemeContext);
    // 待办列表数据
    const [todos, setTodos] = useState<Todo[]>([]);
    // 输入框内容
    const [newTodo, setNewTodo] = useState<string>("");

    // 添加待办项
    const handleAdd = () => {
        // 输入为空不添加
        if (newTodo.trim() === "") return;
        const newTodoItem: Todo = {
            // 使用时间戳作为唯一id
            id: Date.now().toString(),
            title: newTodo.trim(),
            isCompleted: false
        }
        setTodos([newTodoItem, ...todos]);
        setNewTodo(""); // 清空输入框
    };

    // 删除待办项
    const handleDelete = (id: string) => {
        setTodos(todos.filter(todo => todo.id !== id));
    };

    // 修改待办项状态
    const handleToggle = (id: string) => {
        setTodos(todos.map(todo => todo.id === id ? { ...todo, isCompleted: !todo.isCompleted } : todo));
    };

    const computedCompletedCount = () => {
        if (todos.length === 0) return { completedCount: 0, unCompletedCount: 0 };
        const completedCount = todos.filter(todo => todo.isCompleted).length;
        const unCompletedCount = todos.length - completedCount;
        return { completedCount, unCompletedCount }
    };
    const { completedCount, unCompletedCount } = computedCompletedCount();

    return (
        <View style={styles.container}>
            <Text style={[styles.title, { color: theme === "light" ? MyColors.black : MyColors.white }]}>Todo List</Text>

            {/* 输入框 + 添加按钮 */}
            <View style={styles.inputContainer}>
                <TextInput
                    style={[styles.input, {
                        color: theme === 'light' ? MyColors.black : MyColors.white,
                        borderColor: theme === 'light' ? MyColors.black : MyColors.white
                    }]}
                    placeholder="添加新待办"
                    placeholderTextColor={theme === 'light' ? MyColors.gray : MyColors.btnGray}
                    value={newTodo}
                    onChangeText={setNewTodo}
                />
                <TouchableOpacity style={styles.addButton} onPress={handleAdd}>
                    <Text style={styles.addButtonText}>+</Text>
                </TouchableOpacity>
            </View>

            {/* 统计 “已完成 / 未完成” 数量 */}
            <View style={styles.countContainer}>
                <Text style={[styles.countText, { color: theme === 'light' ? MyColors.black : MyColors.white }]}>已完成 {completedCount} / 未完成 {unCompletedCount}</Text>
            </View>

            {/* 待办列表 */}
            <FlatList
                data={todos}
                renderItem={({ item }) => (
                    <TodoItem
                        title={item.title}
                        isCompleted={item.isCompleted}
                        onDelete={() => handleDelete(item.id)}
                        onToggle={() => handleToggle(item.id)}
                    />
                )}
                keyExtractor={todo => todo.id}
                style={styles.list}
            />
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 24,
    },
    title: {
        fontWeight: 'bold',
        fontSize: 24,
        marginBottom: 24,
        textAlign: 'center',
    },
    inputContainer: {
        flexDirection: 'row',
        marginBottom: 24,
    },
    input: {
        flex: 1,
        height: 40,
        borderWidth: 1,
        borderRadius: 4,
        paddingHorizontal: 8,
        marginRight: 8,
    },
    addButton: {
        width: 40,
        height: 40,
        borderRadius: 4,
        backgroundColor: MyColors.blue,
        justifyContent: 'center',
        alignItems: 'center',
    },
    addButtonText: {
        color: MyColors.white,
        fontSize: 24,
    },
    countContainer: {
        marginBottom: 16,
    },
    countText: {
        fontStyle: 'italic',
        textAlign: 'center',
    },
    list: {
        flex: 1
    }
})